var wxCharts = require('../../utils/wxcharts.js');
var app = getApp();
var columnChart = null;
const db = wx.cloud.database();
Page({
    data: {
        openid:"",
        arrayCategories:[],
        arraySeries:[],
    },
    onReady: function (e) {
       // this.getOpenid();
       
    },
    onShow:function(e){
      this.loadData(this.setChart);
    },
   loadData(successCallBack){
       var _this = this;
        db.collection("sport").where({
           _openid: this.data.openid,
        }).orderBy("createtm","desc").get({
            success: function(res) {
              console.log(res.data);
              _this.loadDataResult(res.data);
              successCallBack();
            }
          })
    },
    loadDataResult(datas){
      if(datas==null){
        return;
      }
      var hash=[];
      var sportObj = new Object();
      var sport =[];
      for(var i=0;i<datas.length;i++){
        var data = datas[i];
        //日期数据合并
        if(hash.indexOf(data.createDate)==-1){
            hash.push(data.createDate);
            sportObj[data.createDate] = data.times;
         }else{
            sportObj[data.createDate] = sportObj[data.createDate] + data.times;
         }
      }
      for(var key in sportObj){
        sport.push( (sportObj[key]/1000/60).toFixed(2) );
      }
      this.setData({
        arrayCategories:hash,
        arraySeries:sport,
      })
    },
    setChart(){
      var windowWidth = 640;
      try {
        var res = wx.getSystemInfoSync();
        windowWidth = res.windowWidth;
      } catch (e) {
        console.error('getSystemInfoSync failed!');
      }
      console.log(this.data.arrayCategories);
      columnChart = new wxCharts({
          canvasId: 'columnCanvas',
          type: 'column',
          animation: true,
          categories: (this.data.arrayCategories).reverse(),
          series: [{
              name: '锻炼时长（分）',
              data: (this.data.arraySeries).reverse(),
          }],
          yAxis: {
              format: function (val) {
                  return val;
              },
              title: '锻炼时长（分）',
              min: 0
          },
          xAxis: {
              disableGrid: true,
              type: 'calibration'
          },
          extra: {
              column: {
                  width: 30
              }
          },
          width: windowWidth,
          height: 200,
      });
    },
    getOpenid(){
        let that = this;
        wx.cloud.callFunction({
          name:'getOpenid',
          complete:res=>{
            console.log('云函数获取到的openid:',res.result.openid)
            var openid = res.result.openid;
            that.setData({
              openid:openid
            })
          }
        })
    },
});